//simplewebserver package
//This file implements cryption
package simplewebserver

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "io"
    "log"
)

var key = []byte{170,89,45,202,121,74,30,5,192,53,100,58,155,31,94,245}
var iv = []byte{81,199,207,175,80,155,193,108,255,198,37,199,99,191,125,240}

func randKey(size int) []byte{
    key := make([]byte, size)
    if _, err := io.ReadFull(rand.Reader, key); err != nil {
        log.Println(err)
    }
    return key
}

func Encrypt(text []byte) ([]byte, error){
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    b := base64.StdEncoding.EncodeToString(text)
    ciphertext := make([]byte, len(b))
    cfb := cipher.NewCFBEncrypter(block, iv)
    cfb.XORKeyStream(ciphertext, []byte(b))
    return ciphertext, nil
}

func Decrypt(text []byte) ([]byte, error){
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    cfb := cipher.NewCFBDecrypter(block, iv)
    res := make([]byte, len(text))
    cfb.XORKeyStream(res, text)
    data, err := base64.StdEncoding.DecodeString(string(res))
    if err != nil {
        return nil, err
    }
    return data, nil
}